from rest_framework import serializers
from django.core.exceptions import ValidationError
from .models import Deck, DeckCard
from apps.cards.serializers import CardSerializer


class DeckCardSerializer(serializers.ModelSerializer):
    """卡组卡牌序列化器"""
    card = CardSerializer(read_only=True)
    card_id = serializers.IntegerField(write_only=True)
    
    class Meta:
        model = DeckCard
        fields = ('id', 'card', 'card_id', 'quantity')
        read_only_fields = ('id',)


class DeckSerializer(serializers.ModelSerializer):
    """卡组序列化器"""
    deck_cards = DeckCardSerializer(many=True, read_only=True)
    total_cards = serializers.ReadOnlyField()
    is_valid = serializers.ReadOnlyField()
    validation_errors = serializers.ReadOnlyField()
    
    class Meta:
        model = Deck
        fields = ('id', 'name', 'deck_cards', 'total_cards', 'is_valid', 'validation_errors', 'is_active', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')
    
    def validate(self, attrs):
        # 验证卡组名称唯一性
        if 'name' in attrs:
            existing_deck = Deck.objects.filter(
                user=self.context['request'].user,
                name=attrs['name']
            ).exclude(id=self.instance.id if self.instance else None)
            if existing_deck.exists():
                raise serializers.ValidationError("卡组名称已存在")
        
        # 检查用户卡组数量限制
        if not self.instance:  # 新建卡组时检查
            user_deck_count = Deck.objects.filter(user=self.context['request'].user, is_active=True).count()
            if user_deck_count >= 10:
                raise serializers.ValidationError("每个用户最多只能拥有10个卡组")
        
        return attrs


class DeckCardAddSerializer(serializers.Serializer):
    """添加卡牌到卡组序列化器"""
    card_id = serializers.IntegerField()
    quantity = serializers.IntegerField(min_value=1, max_value=1, default=1)
    
    def validate_card_id(self, value):
        from apps.cards.models import Card, UserCard
        
        # 检查卡牌是否存在
        try:
            card = Card.objects.get(id=value, is_active=True)
        except Card.DoesNotExist:
            raise serializers.ValidationError("卡牌不存在")
        
        # 检查用户是否拥有该卡牌
        user = self.context['request'].user
        try:
            user_card = UserCard.objects.get(user=user, card=card)
        except UserCard.DoesNotExist:
            raise serializers.ValidationError("您没有这张卡牌")
        
        return value


class DeckCreateSerializer(serializers.ModelSerializer):
    """创建卡组序列化器"""
    
    class Meta:
        model = Deck
        fields = ('name',)
    
    def validate_name(self, value):
        # 检查卡组名称是否已存在
        user = self.context['request'].user
        if Deck.objects.filter(user=user, name=value, is_active=True).exists():
            raise serializers.ValidationError("卡组名称已存在")
        
        # 检查用户卡组数量限制
        user_deck_count = Deck.objects.filter(user=user, is_active=True).count()
        if user_deck_count >= 10:
            raise serializers.ValidationError("每个用户最多只能拥有10个卡组")
        
        return value


class DeckValidationSerializer(serializers.Serializer):
    """卡组验证序列化器"""
    deck_id = serializers.IntegerField()
    
    def validate_deck_id(self, value):
        try:
            deck = Deck.objects.get(id=value, user=self.context['request'].user)
        except Deck.DoesNotExist:
            raise serializers.ValidationError("卡组不存在")
        return value
